package com.medvalley.tcm.service.impl;

import com.medvalley.tcm.base.BusinessException;
import com.medvalley.tcm.base.QuestionType;
import com.medvalley.tcm.dao.AppointmentDao;
import com.medvalley.tcm.dao.QuestionnaireDao;
import com.medvalley.tcm.dao.SickInfoDao;
import com.medvalley.tcm.dao.UserInfoDao;
import com.medvalley.tcm.domain.Appointment;
import com.medvalley.tcm.domain.Questionnaire;
import com.medvalley.tcm.domain.SickInfo;
import com.medvalley.tcm.domain.UserInfo;
import com.medvalley.tcm.service.QuestionnaireService;
import com.medvalley.tcm.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by LinSong on 2018/3/6.
 */
@Service
public class QuestionnaireServiceImpl implements QuestionnaireService {

    private static Logger LOGGER = LoggerFactory.getLogger(QuestionnaireServiceImpl.class);
    @Autowired
    private QuestionnaireDao questionnaireDao;

    @Autowired
    private SickInfoDao sickInfoDao;

    @Autowired
    private AppointmentDao appointmentDao;

    @Autowired
    private MusicService musicService;

    @Autowired
    private UserInfoDao userInfoDao;


    @Override
    @Transactional
    public String createQuestionnaire(Questionnaire questionnaire) {
        String result = "";
        long createTime = System.currentTimeMillis();
        questionnaire.setCreateTime(createTime);
        String org = questionnaire.getOrg();
        String userNumber = questionnaire.getUserNumber();
        if ("hyg".equals(org)) {
            questionnaireDao.save(questionnaire);
        } else {
            List<Questionnaire> questionnaireList = questionnaireDao.getOneByUserNumberAndOrg(userNumber, org);
            if (CollectionUtils.isEmpty(questionnaireList)) {
                questionnaireDao.save(questionnaire);
            } else {
                questionnaire.setId(questionnaireList.get(0).getId());
                questionnaireDao.save(questionnaire);
            }
        }
        // 推荐音乐
        if ("app".equals(questionnaire.getSrc())) {
            try {
                String phone = questionnaire.getUserNumber();
                UserInfo userInfo = userInfoDao.findOneByPhone(phone);
                if (userInfo != null && !StringUtils.isEmpty(questionnaire.getConfirm())) {
                    musicService.recommendMusic(userInfo.getId(), QuestionType.BODY.getCode(), questionnaire.getConfirm());
                }
            } catch (Exception e) {
                LOGGER.error("recommend music error at tizhi,user number [{}] ", userNumber, e);
            }
        }
        SickInfo sickInfo = sickInfoDao.findOneByBarCode(questionnaire.getUserNumber());
        if (sickInfo != null) {
            if (StringUtils.isEmpty(sickInfo.getPhysiqueType())) {
                sickInfo.setPhysiqueType(questionnaire.getAnswer());
                sickInfoDao.save(sickInfo);
            } else {
                result = "该条码已使用，本次检查结果仅供临时参考";
            }
        } else {
            LOGGER.warn(" sickInfo is null,barcode:{},src:{}", questionnaire.getUserNumber(), questionnaire.getSrc());
        }
        return result;
    }

    @Override
    public Questionnaire getQuestionnaireByUserNumber(String userNumber, String org) {
        List<Questionnaire> questionnaires = questionnaireDao.getOneByUserNumberAndOrg(userNumber, org);
        if (!CollectionUtils.isEmpty(questionnaires)) {
            return questionnaires.get(0);
        }
        return null;

    }

    @Override
    public List<Questionnaire> findMyselfQuestionnaire(String userNumber, int edition, String org) {
        String src = "app";
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(0, 30, sort);
        if (edition == -1) {
            List<Questionnaire> questionnaires = questionnaireDao.findAllByUserNumberAndOrgAndSrc(userNumber, org, src, pageable);
            return questionnaires;
        } else {
            List<Questionnaire> questionnaires = questionnaireDao.findAllByUserNumberAndEditionAndOrgAndSrc(userNumber, edition, org, src, pageable);
            return questionnaires;
        }
    }

    @Override
    public Questionnaire findOneMyselfQuestionnaire(String userNumber, long id) {
        Questionnaire questionnaire = questionnaireDao.findById(id).orElseThrow(() -> new BusinessException("没有体检数据"));
        if (questionnaire.getUserNumber().equals(userNumber)) {
            return questionnaire;
        } else {
            throw new BusinessException("此体检数据不属于您");
        }
    }

    @Override
    public boolean checkBarcode(String barcode) {

        Appointment appointment = appointmentDao.findOneByBarcode(barcode);
        if (appointment == null) {
            return false;
        }
        SickInfo sickInfo = sickInfoDao.findOneByBarCode(barcode);
        if (sickInfo == null) {
            return false;
        }
        return true;
    }

}
